<template>
  <div class="code-snippets-page">
    <div class="code-snippets">
      <div class="snippets-header">
        <h1>代码片段</h1>
        <p class="subtitle">实用代码示例与解决方案</p>
      </div>

      <div class="snippets-filters">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索代码片段..."
            @input="filterSnippets"
          >
        </div>
        <div class="language-filter">
          <button 
            v-for="lang in languages" 
            :key="lang"
            :class="['filter-btn', { active: currentLanguage === lang }]"
            @click="currentLanguage = lang"
          >
            {{ lang }}
          </button>
        </div>
      </div>

      <div class="snippets-grid">
        <div 
          v-for="snippet in filteredSnippets" 
          :key="snippet.id" 
          class="snippet-card"
        >
          <div class="snippet-header">
            <h3>{{ snippet.title }}</h3>
            <div class="snippet-actions">
              <button 
                class="action-btn copy-btn" 
                @click="copyCode(snippet.code)"
                title="复制代码"
              >
                <i class="btn-icon">📋</i>
                复制
              </button>
            </div>
          </div>
          <p class="snippet-desc">{{ snippet.description }}</p>
          <pre class="code-block"><code 
            :class="snippet.language"
            v-html="highlightCode(snippet.code, snippet.language)"
          ></code></pre>
          <div class="snippet-footer">
            <div class="snippet-tags">
              <span 
                v-for="tag in snippet.tags" 
                :key="tag" 
                class="tag"
              >
                {{ tag }}
              </span>
            </div>
            <span class="version">v{{ snippet.version }}</span>
          </div>
        </div>
      </div>

      <!-- 代码演示弹窗 -->
      <div v-if="showDemoModal" class="demo-modal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>{{ currentDemo.title }} 演示</h3>
            <button class="close-btn" @click="closeDemoModal">×</button>
          </div>
          <div class="demo-container">
            <div class="code-editor">
              <textarea 
                v-model="demoCode" 
                @input="updatePreview"
                spellcheck="false"
              ></textarea>
            </div>
            <div class="preview-container">
              <iframe ref="previewFrame" sandbox="allow-scripts"></iframe>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { siteConfig } from '../config/site'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css' // 改用 github-dark 主题
import { useToast } from '../composables/useToast'

const toast = useToast()

// 直接使用响应式引用
const snippets = ref(siteConfig.codeSnippets)
const searchQuery = ref('')
const currentLanguage = ref('全部')
const showDemoModal = ref(false)
const currentDemo = ref(null)
const demoCode = ref('')
const previewFrame = ref(null)

// 调试输出
onMounted(() => {
  console.log('Code snippets data:', snippets.value)
})

// 获取所有编程语言
const languages = computed(() => {
  if (!snippets.value) return ['全部']
  const langs = ['全部', ...new Set(snippets.value.map(s => s.language))]
  return langs
})

// 过滤代码片段
const filteredSnippets = computed(() => {
  if (!snippets.value) return []
  let filtered = snippets.value

  if (currentLanguage.value !== '全部') {
    filtered = filtered.filter(s => s.language === currentLanguage.value)
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(s => 
      s.title.toLowerCase().includes(query) ||
      s.description.toLowerCase().includes(query) ||
      s.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }

  return filtered
})

// 代码高亮处理
const highlightCode = (code, language) => {
  try {
    if (language) {
      return hljs.highlight(code, { language }).value
    }
    return hljs.highlightAuto(code).value
  } catch (err) {
    console.warn('Code highlight error:', err)
    return code
  }
}

// 复制代码到剪贴板
const copyCode = async (code) => {
  try {
    await navigator.clipboard.writeText(code.trim())
    toast.show('代码已复制到剪贴板')
  } catch (err) {
    toast.show('复制失败，请手动复制', 'error')
    console.error('Copy error:', err)
  }
}

// 显示演示
const showDemo = (snippet) => {
  currentDemo.value = snippet
  demoCode.value = snippet.code
  showDemoModal.value = true
  updatePreview()
}

// 关闭演示弹窗
const closeDemoModal = () => {
  showDemoModal.value = false
  currentDemo.value = null
  demoCode.value = ''
}

// 更新预览
const updatePreview = () => {
  if (!previewFrame.value) return
  
  const preview = previewFrame.value
  const code = demoCode.value
  
  // 根据代码类型生成预览HTML
  let demoHtml = ''
  if (currentDemo.value.language === 'css') {
    demoHtml = `<style>${code}</style><div class="preview-content"></div>`
  } else if (currentDemo.value.language === 'html') {
    demoHtml = code
  } else {
    demoHtml = `<script>${code}<\/script>` // 注意这里需要转义结束标签
  }
    
  const htmlContent = `
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      body { margin: 0; padding: 16px; font-family: sans-serif; }
    </style>
  </head>
  <body>${demoHtml}</body>
</html>`

  preview.srcdoc = htmlContent
}
</script>

<style lang="scss" scoped>
.code-snippets-page {
  width: 100%;
}

.code-snippets {
  padding: 80px 20px;
  max-width: 1200px;
  margin: 0 auto;

  .snippets-header {
    text-align: center;
    margin-bottom: 4rem;

    h1 {
      font-size: 3rem;
      color: var(--primary-color);
      margin-bottom: 1rem;
    }

    .subtitle {
      font-size: 1.5rem;
      color: var(--text-color);
      opacity: 0.8;
    }
  }
}

.snippets-filters {
  margin-bottom: 3rem;

  .search-box {
    margin-bottom: 2rem;
    
    input {
      width: 100%;
      padding: 1rem;
      border: 2px solid rgba(var(--primary-color-rgb), 0.1);
      border-radius: 10px;
      font-size: 1.1rem;
      background: var(--background-color);
      color: var(--text-color);
      
      &:focus {
        outline: none;
        border-color: var(--primary-color);
      }
    }
  }

  .language-filter {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;

    .filter-btn {
      padding: 0.8rem 1.5rem;
      border: none;
      border-radius: 25px;
      background: var(--background-color);
      color: var(--text-color);
      font-size: 1.1rem;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
      }

      &.active {
        background: var(--primary-color);
        color: white;
      }
    }
  }
}

.snippets-grid {
  display: grid;
  gap: 2rem;

  .snippet-card {
    background: var(--background-color);
    border-radius: 20px;
    padding: 2rem;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .snippet-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1rem;

      h3 {
        font-size: 1.6rem;
        color: var(--text-color);
      }

      .snippet-actions {
        display: flex;
        gap: 1rem;

        .action-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.6rem 1rem;
          border: none;
          border-radius: 15px;
          background: rgba(var(--primary-color-rgb), 0.1);
          color: var(--primary-color);
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            background: var(--primary-color);
            color: white;
          }
        }
      }
    }

    .snippet-description {
      font-size: 1.1rem;
      color: var(--text-color);
      opacity: 0.8;
      margin-bottom: 1.5rem;
    }

    .copy-btn {
      position: relative;
      overflow: hidden;
      
      &:active {
        transform: scale(0.95);
      }
      
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.2);
        transform: translate(-50%, -50%) scale(0);
        border-radius: 50%;
        transition: transform 0.3s ease;
      }
      
      &:active::after {
        transform: translate(-50%, -50%) scale(2);
      }
    }

    .code-block {
      position: relative;
      background: var(--code-bg, #282c34);
      padding: 1rem;
      border-radius: 8px;
      margin: 1rem 0;
      
      @media (prefers-color-scheme: light) {
        --code-bg: #f6f8fa;
      }
      
      &:hover .copy-btn {
        opacity: 1;
      }

      code {
        font-family: 'Fira Code', 'Source Code Pro', monospace;
        font-size: 0.95rem;
        line-height: 1.5;
        tab-size: 2;
        
        :deep(pre), :deep(code) {
          background: transparent;
        }
        
        :deep(.hljs) {
          background: transparent;
          color: #abb2bf;
        }
        
        :deep(.hljs-keyword) {
          color: #c678dd;
        }
        
        :deep(.hljs-string) {
          color: #98c379;
        }
        
        :deep(.hljs-number) {
          color: #d19a66;
        }
        
        :deep(.hljs-function) {
          color: #61afef;
        }
        
        :deep(.hljs-comment) {
          color: #5c6370;
          font-style: italic;
        }
      }
    }

    .snippet-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .tags {
        display: flex;
        gap: 0.8rem;
        flex-wrap: wrap;

        .tag {
          padding: 0.4rem 1rem;
          background: rgba(var(--primary-color-rgb), 0.1);
          color: var(--primary-color);
          border-radius: 15px;
          font-size: 0.9rem;
        }
      }

      .version {
        font-size: 0.9rem;
        color: var(--text-color);
        opacity: 0.6;
      }
    }
  }
}

.demo-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .modal-content {
    background: var(--background-color);
    border-radius: 20px;
    width: 90%;
    max-width: 1200px;
    max-height: 90vh;
    overflow: hidden;

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1.5rem 2rem;
      border-bottom: 1px solid rgba(var(--primary-color-rgb), 0.1);

      h3 {
        font-size: 1.6rem;
        color: var(--text-color);
      }

      .close-btn {
        font-size: 2rem;
        background: none;
        border: none;
        color: var(--text-color);
        cursor: pointer;
        opacity: 0.6;
        transition: opacity 0.3s;

        &:hover {
          opacity: 1;
        }
      }
    }

    .demo-container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 2rem;
      padding: 2rem;
      height: 60vh;

      .code-editor {
        textarea {
          width: 100%;
          height: 100%;
          padding: 1rem;
          border: 2px solid rgba(var(--primary-color-rgb), 0.1);
          border-radius: 10px;
          font-family: 'Fira Code', monospace;
          font-size: 1rem;
          line-height: 1.5;
          resize: none;
          background: #1e1e1e;
          color: #d4d4d4;

          &:focus {
            outline: none;
            border-color: var(--primary-color);
          }
        }
      }

      .preview-container {
        iframe {
          width: 100%;
          height: 100%;
          border: 2px solid rgba(var(--primary-color-rgb), 0.1);
          border-radius: 10px;
          background: white;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .code-snippets {
    padding: 40px 1rem;

    .snippets-header {
      h1 {
        font-size: 2.2rem;
      }
    }
    
    .code-block {
      code {
        font-size: 0.85rem;
      }
    }
  }

  .snippets-filters {
    .language-filter {
      .filter-btn {
        padding: 0.6rem 1rem;
        font-size: 1rem;
      }
    }
  }

  .demo-modal {
    .modal-content {
      .demo-container {
        grid-template-columns: 1fr;
        height: 70vh;
      }
    }
  }
}

// 添加暗色主题支持
:root {
  --code-bg: #282c34;
}

:root[data-theme="light"] {
  --code-bg: #f6f8fa;
}
</style> 